<template>
  <s-layout title="使用优惠券和积分">
    <view
      class="bg-white address-box ss-m-b-14 ss-r-b-10"
      @tap="onSelectAddress"
    >
	    <s-coupon-old-list
			    :choose="true"
			    :data="state.addressInfo"
	    ></s-coupon-old-list>
    </view>
    <view class="order-card-box ss-m-b-14">

      <!--<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
        <view class="item-title">剩余积分</view>
        <view class="ss-flex ss-col-center">
          <view class="item-value ss-m-r-24">{{ userInfo.score }}分</view>
        </view>
      </view>-->

	    <!--<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
		    <view class="item-title">本次使用积分</view>
		    <view class="ss-flex ss-col-center">
			    <uni-easyinput
						maxlength="20"
						type="digit"
						placeholder="1积分抵扣1元"
						v-model="state.orderPayload.score"
						@blur="onChangeScore"
						:inputBorder="false"
						:clearable="false"
					></uni-easyinput>
		    </view>
	    </view>-->

    </view>

	  <view class="bg-white total-card-box ss-p-20 ss-m-b-14 ss-r-10">
      <view class="total-box-content border-bottom">
	      <view class="order-item ss-flex ss-col-center ss-row-between">
		      <view class="item-title">运费金额</view>
		      <view class="ss-flex ss-col-center">
			      <text class="item-value ss-m-r-24">￥{{ state.orderInfo.freightAmount }}</text>
		      </view>
	      </view>
	      <view v-if="state.orderInfo.couponAmount" class="order-item ss-flex ss-col-center ss-row-between">
		      <view class="item-title">优惠券抵扣</view>
		      <view class="ss-flex ss-col-center money">
			      <text class="item-value ss-m-r-24">-￥{{ state.orderInfo.couponAmount }}</text>
		      </view>
	      </view>
	      <view v-if="state.orderInfo.scoreAmount" class="order-item ss-flex ss-col-center ss-row-between">
		      <view class="item-title">积分抵扣</view>
		      <view class="ss-flex ss-col-center money">
			      <text class="item-value ss-m-r-24">-￥{{ state.orderInfo.scoreAmount }}</text>
		      </view>
	      </view>
        <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">应付金额</view>
          <view class="ss-flex ss-col-center">
            <text class="item-value ss-m-r-24">￥{{ state.orderInfo.payAmount }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <su-fixed bottom :opacity="false" bg="bg-white" placeholder :noFixed="false" :index="200">
      <view class="footer-box border-top ss-flex ss-row-between ss-p-x-20 ss-col-center">
        <button
          class="add-btn ss-reset-button ui-Shadow-Main"
          @tap="onConfirm"
        >
	        立即支付
        </button>
      </view>
    </su-fixed>
  </s-layout>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import {clone, isEmpty} from 'lodash';

  const userInfo = computed(() => sheep.$store('user').userInfo);

  const state = reactive({
    orderPayload: {},
	  payMetaData: {},
    orderInfo: {},
	  tableInfo: [],
    addressInfo: {
			name: '点击选择运费抵扣券'
    },
	  tableData: [],
    invoiceInfo: {},
    totalNumber: 0,
    showCoupon: false,
    couponInfo: [],
    showDiscount: false,
	  sendTypeList: [
		  {
			  text: '直邮',
			  value: 0,
		  },
      {
        text: '拼邮',
        value: 1,
      }
	  ],
  });

  // 立即兑换(立即兑换无需跳转收银台)
  const exchangeNow = computed(
    () => state.orderPayload.order_type == 'score' && state.orderInfo.pay_fee == 0,
  );

  //选择售后类型
  function onRefundChange(e) {
	  state.orderPayload.sendType = e.detail.value;
  }

	async function onChangeScore(e) {
		console.log(e, '积分变化')
		if (e.detail.value <= 0) {
			sheep.$helper.toast('积分必须大于0');
			state.orderPayload.score = 0;
		} else if (e.detail.value > userInfo.score) {
			sheep.$helper.toast('最多可使用' + userInfo.score + '积分');
			state.orderPayload.score = userInfo.score;
		} else {
			state.orderPayload.score = e.detail.value;
		}
		// 使用优惠券和积分
		if (state.orderPayload.score) {
			let res = await sheep.$api.order.useCouponAndScore({
				expressNo: state.payMetaData.expressNo,
				score: state.orderPayload.score,
				couponId: state.orderPayload.couponId
			});
			console.log(res, '积分')
			if (res.id) {
				state.orderInfo = res;
			}
		}
	}

  // 选择地址
  function onSelectAddress() {
    uni.$once('SELECT_COUPON', (e) => {
      changeConsignee(e.addressInfo);
    });
    sheep.$router.go('/pages/coupon/backup/list');
  }

  // 更改收货人地址&计算包裹信息
  async function changeConsignee(addressInfo = {}) {
    if (!isEmpty(addressInfo)) {
      state.orderPayload.couponId = addressInfo.id;
			// 使用优惠券和积分
      if (state.orderPayload.couponId) {
				let res = await sheep.$api.order.useCouponAndScore({
					expressNo: state.payMetaData.expressNo,
					score: state.orderPayload.score,
					couponId: state.orderPayload.couponId
				});
				if (res.id) {
					state.orderInfo = res;
					state.addressInfo = addressInfo;
				}
      }
    }
  }

  // 支付运费
  function onDeyPay() {
	  sheep.$router.go('/pages/pay/index', {
		  orderSN: state.payMetaData.orderSn,
		  totalAmount: state.orderInfo.payAmount,
		  expressNo: state.payMetaData.expressNo,
		  couponId: state.orderPayload.couponId,
		  score: state.orderPayload.score,
		  orderType: 'memberConsumerDeyPay'
	  });
  }

  // 选择优惠券
  async function onSelectCoupon(e) {
    state.orderPayload.coupon_id = e || 0;
    getOrderInfo();
    state.showCoupon = false;
  }

  // 选择发票信息
  function onSelectInvoice() {
    uni.$once('SELECT_INVOICE', (e) => {
      state.invoiceInfo = e.invoiceInfo;
      state.orderPayload.invoice_id = e.invoiceInfo.id || 0;
    });
    sheep.$router.go('/pages/user/invoice/list');
  }

  // 提交包裹/立即兑换
  function onConfirm() {
	    uni.showModal({
	      title: '提示',
	      content: '确认使用这些优惠进行运费结算么',
	      cancelText: '再想想',
	      success: async function (res) {
	        if (res.confirm) {
	          submitOrder();
	        }
	      },
	    });
  }

  // 创建包裹&跳转
  async function submitOrder() {
	  sheep.$api.order.useCouponAndScore({
		  expressNo: state.payMetaData.expressNo,
		  score: state.orderPayload.score,
		  couponId: state.orderPayload.couponId
	  }).then(resp => {
			if (resp.id) {
				let obj = JSON.stringify({
					expressNo: state.payMetaData.expressNo,
					score: state.orderPayload.score,
					couponId: state.orderPayload.couponId,
				})
				sheep.$router.go('/pages/pay/index', {
					orderSN:state.payMetaData.orderSN,
					totalAmount: state.orderInfo.payAmount,
					couponData: obj,
					orderType: 'memberConsumerDeyPay'
				});
			}
	  })
  }

  // 检查库存&计算包裹价格
  async function getOrderInfo() {
    const skuList = state.orderPayload.goods_list.map(it => {return {skuId: it.skuId, quantity:it.goods_num}})
    let res = await sheep.$api.order.calc({skuList});
    if (!res) {
      setTimeout( () => {
        sheep.$router.back()
      }, 2000)
      return
    }
    state.totalNumber = 0
    state.orderInfo = res
    state.orderInfo.skuList.forEach( (item) => {
      let str = '默认规格'
      /*const obj = JSON.parse(item.spData)
      Object.keys(obj).forEach((key) => {
        str += key + ": " + obj[key] + "  "
      })*/
      item.spDataValue = str
      state.totalNumber += item.quantity
    })
  }

  // 获取可用优惠券
  async function getCoupons() {
    const { error, data } = await sheep.$api.order.coupons(state.orderPayload);
    if (error == 0) {
      state.couponInfo = data;
    }
  }

  onLoad(async (options) => {
    if (options.expressNo) {
      state.payMetaData = options;
	    console.log(state.payMetaData, '支付数据')
	    // 查询包裹信息
	    const res = await sheep.$api.order.expressDetail({orderId: options.expressNo});
			state.orderInfo = res
    }
  });
</script>

<style lang="scss" scoped>
  :deep() {
    .uni-input-wrapper {
      width: 320rpx;
    }

    .uni-easyinput__content-input {
      font-size: 28rpx;
      height: 72rpx;
      text-align: right !important;
      padding-right: 0 !important;

      .uni-input-input {
        font-weight: 500;
        color: #333333;
        font-size: 26rpx;
        height: 32rpx;
        margin-top: 4rpx;
      }
    }
    .uni-easyinput__content {
      display: flex !important;
      align-items: center !important;
      justify-content: right !important;
    }
  }
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .order-item {
    height: 80rpx;

    .item-title {
      font-size: 28rpx;
      font-weight: 400;
    }

    .item-value {
      font-size: 28rpx;
      font-weight: 500;
    }

    .item-value {
      font-family: OPPOSANS;
    }
    .text-disabled {
      color: #bbbbbb;
    }

    .item-icon {
      color: $dark-9;
    }

    .remark-input {
      text-align: right;
    }

    .item-placeholder {
      color: $dark-9;
      font-size: 26rpx;
      text-align: right;
    }
  }

  .total-box-footer {
    height: 90rpx;

    .total-num {
      color: #333333;
      font-family: OPPOSANS;
    }
  }

  .footer-box {
    height: 100rpx;

    .submit-btn {
      width: 240rpx;
      height: 70rpx;
      font-size: 28rpx;
      font-weight: 500;

      .goto-pay-text {
        line-height: 28rpx;
      }
    }

    .cancel-btn {
      width: 240rpx;
      height: 80rpx;
      font-size: 26rpx;
      background-color: #e5e5e5;
      color: $dark-9;
    }
  }
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  .subtitle {
    font-size: 28rpx;
    color: #999999;
  }
  .cicon-checkbox {
    font-size: 36rpx;
    color: var(--ui-BG-Main);
  }
  .cicon-box {
    font-size: 36rpx;
    color: #999999;
  }
  .add-btn {
	  flex: 1;
	  background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
	  border-radius: 80rpx;
	  font-size: 30rpx;
	  font-weight: 500;
	  line-height: 80rpx;
	  color: $white;
	  position: relative;
	  z-index: 1;
  }

  .money {
	  color: #ff0010;
	  font-weight: bold;
  }
</style>
